#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>


int main() {
	int sock, listener;
	struct sockaddr_in addr;
	char buf[1024];
	int bytes_read, bytes_sent;

	listener = socket(AF_INET, SOCK_DGRAM, 0);
	if (listener < 0) {
		perror("initialization of socket failed");
		exit(errno);
	}
	printf("listen\n");
	addr.sin_family = AF_INET;
	addr.sin_port = htons(6006);
	addr.sin_addr.s_addr = INADDR_ANY;
	if (bind(listener, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
		perror("bind failed");
		exit(errno);
	}
	printf("bind\n");
	struct sockaddr from_addr;
	int addr_len = sizeof(from_addr);
	while (1) {
		bytes_read = recvfrom(listener, (void *)buf, 1024, 0, &from_addr, (socklen_t*)&addr_len);
		if (bytes_read < 0) {
			perror("read failed");
			exit(errno);	
		}
		printf("%s\n", buf);
		bytes_sent = sendto(listener, (void *)buf, sizeof(buf), 0, &from_addr, (socklen_t)addr_len);
	}
	close(sock);
	return 0;
}
